
package com.yunkazaixian.syntelecom.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dyvmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dyvmsapi20170525.models.SingleCallByTtsRequest;
import com.aliyun.sdk.service.dyvmsapi20170525.models.SingleCallByTtsResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yunkazaixian.syntelecom.entity.*;
import com.yunkazaixian.syntelecom.mapper.McProductNormsMapper;
import com.yunkazaixian.syntelecom.mapper.McSimDxMapper;
import com.yunkazaixian.syntelecom.mapper.McSmsMapper;
import com.yunkazaixian.syntelecom.rabbitmq.MqMessageProducer;
import com.yunkazaixian.syntelecom.service.*;
import com.yunkazaixian.syntelecom.service.impl.SessionService;
import com.yunkazaixian.syntelecom.utils.*;
import darabonba.core.client.ClientOverrideConfiguration;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Lin
 * @since 2022-10-01
 */
@Slf4j
@Api(tags = "推送", description = "推送信息")
@RestController
@RequestMapping("/api/push")
public class PushController {
    @Autowired
    McSimDxMapper simDxMapper;
    @Autowired
    McSmsMapper smsMapper;
    @Value("${zhongrui-push.server}")
    private String server;
    @Autowired
    DXService dxService;
    @Autowired
    McProductNormsMapper mcProductNormsMapper;
    @Autowired
    private IMcSimDxService mcSimDxService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MqMessageProducer messageProducer;
    @Autowired
    private ISysTenantConfigService sysTenantConfigService;
    @Autowired
    private ISysTenantService sysTenantService;
    @Autowired
    private IMcSimExceptionService mcSimExceptionService;
    @Autowired
    private IMcCallPhoneSettingService mcCallPhoneSettingService;
    @Autowired
    private SessionService sessionService;
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;
    @Autowired
    private RequestQueueService requestQueueService;
    @PostMapping(value = "/zhongrui", consumes = {MediaType.APPLICATION_XML_VALUE})
    @ResponseBody
    public Object zhongrui(@RequestBody Push push) {

        if (push == null || StringUtils.isEmpty(push.getIccid())) {
            return null;
        }
        String phone = push.getIccid().trim();
        SimFlowDetail simFlowDetail = new SimFlowDetail();//(SimFlowDetail) ((HttpResponse) apiController.detail(phone)).getData();
        simFlowDetail.setIccid(push.getIccid());
        simFlowDetail.setAccess_number(push.getTelephone());
        simFlowDetail.setBalance("0");
        McSimDx one = simDxMapper.selectOne(new LambdaQueryWrapper<McSimDx>().eq(McSimDx::getIccid, push.getIccid()));
        simFlowDetail.setActive_time(one.getActiveTime());
        simFlowDetail.setId(one.getId());
        simFlowDetail.setArrive_time(one.getArriveTime());
        simFlowDetail.setStatus_desc(DXStatusConvertUtils.getStatusDesc(one.getStatus(), one.getActiveTime(), one.getArriveTime()));
        simFlowDetail.setSend_out_time(one.getSendOutTime());
        List<McProductNorms> mcProductNorms = mcProductNormsMapper.selectPackage(new LambdaQueryWrapper<McProductNorms>().eq(McProductNorms::getId, one.getPackageId()));
        if (!ListUtils.isEmpty(mcProductNorms)) {
            McProductNorms norm = mcProductNorms.get(0);
            simFlowDetail.setFlow(norm.getFlow());
            simFlowDetail.setPack_name(norm.getSkuName());
        }
        try {
            simFlowDetail.setUsed(String.valueOf(dxService.queryPakage(push.getIccid(), push.getSendTime().substring(0, 6) + "01")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        //定义请求参数类型，这里用json所以是MediaType.APPLICATION_JSON
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity request = new HttpEntity(FastJsonUtils.toJson(simFlowDetail), headers);
        ResponseEntity<String> entity = client.postForEntity(server, request, String.class);
        //获取3方接口返回的数据通过entity.getBody();它返回的是一个字符串；
        String body = entity.getBody();
        return body;
    }
    /**
     * 状态改为在用
     *
     * @param push
     * @return
     */
    @PostMapping(value = "/updateStatusZaiYong", consumes = {"application/xml", "text/xml"})
    @ResponseBody
    public HttpResponse updateStatusZaiYong(@RequestBody Push push) {
        updateStatus(push, "4");
        return R.ok();
    }

    /**
     * 状态改为运营商管理状态
     *
     * @param push
     * @return
     */
    @PostMapping(value = "/updateStatusGuanKong", consumes = {"application/xml", "text/xml"})
    @ResponseBody
    public HttpResponse updateStatusGuanKong(@RequestBody Push push) {
        try{
            String count = redisUtil.get("guanKong"+DateUtil.today());
            Long countLong = 1L;
            if(StringUtils.isEmpty(count)){
                count = "1";
                countLong = 1L;
            }else{
                countLong = Long.parseLong(count);
                countLong = countLong + 1;
                if(countLong == 500){ // 超过500次，发送语音
                    sendPhone();
                }
            }
            redisUtil.set("guanKong"+DateUtil.today(), countLong.toString(),24 * 60 * 60L);
        }catch (Exception e) {
            log.error("电信回调修改运营商管控状态发送语音失败：{}", e.getMessage());
        }
        updateStatus(push, "6");
        return R.ok();
    }


    /**
     * 状态改为停机
     *
     * @param push
     * @return
     */
    @PostMapping(value = "/updateStatusTingji", consumes = {"application/xml", "text/xml"})
    @ResponseBody
    public HttpResponse updateStatusTingji(@RequestBody Push push) {
        updateStatus(push, "5");
        return R.ok();
    }


    private void updateStatus(Push push, String status) {
        log.info("电信回调修改状态：updateStatus======进入====");
        if (push == null || StringUtils.isEmpty(push.getIccid())) {
            log.info("电信回调修改状态：updateStatus=================ICCID不存在");
            return;
        }
       // log.info("电信回调修改状态：updateStatus==========" + push.getIccid() + "=======" + status);
//        McSimDx one = simDxMapper.selectOne(new LambdaQueryWrapper<McSimDx>().eq(McSimDx::getIccid, push.getIccid()));
//        if (one != null) {

            LambdaUpdateWrapper<McSimDx> lambdaUpdateWrapper = new LambdaUpdateWrapper<McSimDx>()
                    .set(McSimDx::getStatus, status)
                    .set(McSimDx::getStatusChangeTime, push.getSendTime().substring(0, 8))
                    .set(McSimDx::getUpdateTime, new Date())
                    .eq(McSimDx::getIccid, push.getIccid());

            int i = simDxMapper.update(lambdaUpdateWrapper);
            if(i > 0){
                log.info("电信回调：updateStatus==========" + push.getIccid() + "=======" + status + "成功");
            }else{
                log.info("电信回调：updateStatus==========" + push.getIccid() + "=======" + status + "不存在");
            }
//        } else {
//            log.info("电信回调：updateStatus==========" + push.getIccid() + "=======" + status + "不存在");
//        }
    }


    /**
     * 每月使用超过1M激活卡
     *
     * @param push
     * @return
     */
    @PostMapping(value = "/updateArriveTime", consumes = {"application/xml", "text/xml"})
    @ResponseBody
    public HttpResponse updateArriveTime(@RequestBody Push push) {
        log.info("updateArriveTime:=======>" + JSONObject.toJSONString(push));
        return activeSim(push);
    }
    /**
     * SIM卡断网时电信自动化调用
     *
     * @param push
     * @return
     */
    @PostMapping(value = "/disNetwork", consumes = {"application/xml", "text/xml"})
    @ResponseBody
    public HttpResponse disNetwork(@RequestBody Push push) {
        if(push == null || StringUtils.isEmpty(push.getIccid())) {
            return R.fail("上送参数有误");
        }
        McSimDx mcSimDx = new McSimDx();
        mcSimDx.setIccid(push.getIccid());
        mcSimDx.setTelephone(push.getTelephone());
        mcSimDx.setNetworkOutage(1);
        //log.info("disNetwork:=======>" + JSONObject.toJSONString(push));
        try{
            return mcSimDxService.updateMcSimDx(mcSimDx) > 0 ? R.ok() : R.fail();
        }catch (Exception e){
            log.error("disNetwork:=======>" + JSONObject.toJSONString(push), e);
            return R.fail("系统错误");
        }
    }
    /**
     * SIM卡恢复上网时电信自动化调用
     *
     * @param push
     * @return
     */
    @PostMapping(value = "/enableNetwork", consumes = {"application/xml", "text/xml"})
    @ResponseBody
    public HttpResponse enableNetwork(@RequestBody Push push) {
        if(push == null || StringUtils.isEmpty(push.getIccid())) {
            return R.fail("上送参数有误");
        }
        McSimDx mcSimDx = new McSimDx();
        mcSimDx.setIccid(push.getIccid());
        mcSimDx.setTelephone(push.getTelephone());
        mcSimDx.setNetworkOutage(0);
        // log.info("enableNetwork:=======>" + JSONObject.toJSONString(push));
        try{
            return mcSimDxService.updateMcSimDx(mcSimDx) > 0 ? R.ok() : R.fail();
        }catch (Exception e){
            log.error("enableNetwork:=======>" + JSONObject.toJSONString(push), e);
            return R.fail("系统错误");
        }
    }
    /**
     * SIM卡机卡绑定触发推送
     *
     * @param push
     * @return
     */
    @PostMapping(value = "/machineBinding", consumes = {"application/xml", "text/xml"})
    @ResponseBody
    public HttpResponse machineBinding(@RequestBody PushMachine push) {
        if(push == null || StringUtils.isEmpty(push.getIccid())) {
            return R.fail("上送参数有误");
        }
        log.info("machineBinding:=======>" + JSONObject.toJSONString(push));
        McSimDx mcSimDx = new McSimDx();
        mcSimDx.setIccid(push.getIccid());
        mcSimDx.setTelephone(push.getTelephone());
        if(push.getData() != null){
            JSONObject jsonObjectParam = new JSONObject();
            jsonObjectParam.put("flag",5);
            jsonObjectParam.put("iccid", push.getIccid());
            messageProducer.sendMessageToMQDxl(JSONObject.toJSONString(jsonObjectParam),"rk_llk_sim_count_5gCMP_dlx_exchange","sim_5gCMP_llk","1000");
        }else {
            return R.fail("数据错误");
        }
        return R.ok();
    }
    /**
     * SIM卡异常使用风险防控推送
     *
     * @param push
     * @return
     */
    @PostMapping(value = "/abnormalMonitoring", consumes = {"application/xml", "text/xml"})
    @ResponseBody
    public HttpResponse abnormalMonitoring(@RequestBody PushAbnormalMonitoring push) {
        if(push == null || StringUtils.isEmpty(push.getIccid())) {
            return R.fail("上送参数有误");
        }
//        sendPhone();
        McSimDx mcSimDx = new McSimDx();
        mcSimDx.setIccid(push.getIccid());
        mcSimDx.setTelephone(push.getTelephone());
        McSimDx one = simDxMapper.selectOne(new LambdaQueryWrapper<McSimDx>().eq(McSimDx::getIccid, push.getIccid()));
        log.info("abnormalMonitoring:=======>" + JSONObject.toJSONString(push));
        if(one == null){
            log.info("abnormalMonitoring:=======>iccid不存在===" + push.getIccid());
            return R.fail("iccid不存在");
        }
        McSimException mcSimException = new McSimException();
        mcSimException.setIccid(push.getIccid());
        mcSimException.setTelephone(push.getTelephone());
        mcSimException.setExceptionCode("7");
        String exceptionMessage = "";
        if(!StringUtils.isEmpty(push.getAcceptMsg()) && push.getAcceptMsg().contains("手机终端使用监测")){
            exceptionMessage = "手机终端使用监测";
            mcSimException.setExceptionCode("0");
            JSONObject jsonObjectParam = new JSONObject();
            jsonObjectParam.put("flag",5);
            jsonObjectParam.put("iccid", push.getIccid());
            messageProducer.sendMessageToMQDxl(JSONObject.toJSONString(jsonObjectParam),"rk_llk_sim_count_5gCMP_dlx_exchange","sim_5gCMP_llk","1000");
        }
        if(!StringUtils.isEmpty(push.getAcceptMsg()) && push.getAcceptMsg().contains("跨地区使用监测")){
            mcSimException.setExceptionCode("1");
            exceptionMessage = "跨地区使用监测";
        }
        if(!StringUtils.isEmpty(push.getAcceptMsg()) && push.getAcceptMsg().contains("机卡分离监测")){
            mcSimException.setExceptionCode("2");
            exceptionMessage = "机卡分离监测";
        }
        if(!StringUtils.isEmpty(push.getAcceptMsg()) && push.getAcceptMsg().contains("异常使用行为")){
            mcSimException.setExceptionCode("3");
            exceptionMessage = "异常使用行为";
        }
        if(!StringUtils.isEmpty(push.getAcceptMsg()) && push.getAcceptMsg().contains("漫游至诈骗高发区使用")){
            mcSimException.setExceptionCode("4");
            exceptionMessage = "漫游至诈骗高发区使用";
        }
        if(!StringUtils.isEmpty(push.getAcceptMsg()) && push.getAcceptMsg().contains("异常流量使用监测")){
            mcSimException.setExceptionCode("5");
            exceptionMessage = "异常流量使用监测";
        }
        if(!StringUtils.isEmpty(push.getAcceptMsg()) && push.getAcceptMsg().contains("1173不合规")){
            mcSimException.setExceptionCode("6");
            exceptionMessage = "1173不合规";
        }
        mcSimException.setCreateTime(new Date());
        mcSimException.setTenantId(one.getTenantId());
        mcSimException.setCreateDept(Long.parseLong(one.getAgentId()));
        SysTenant sysTenant = null;
        try {
            String jsonObject = redisUtil.get(GlobalConstants.GLOBAL_REDIS_KEY+"tenant_info_"+one.getTenantId());
            JSONArray array = JSONArray.parseArray(jsonObject);
            if (array.size() >= 2) {
                Object secondElement = array.get(1);
                if (secondElement instanceof JSONObject) {
                    JSONObject result = (JSONObject) secondElement;
                    sysTenant = JSONObject.toJavaObject(result, SysTenant.class);
                } else {
                    log.error("第二个元素不是 JSON 对象");
                }
            } else {
                log.error("数组长度不足，无法提取第二个元素");
            }
        } catch (Exception e) {
            log.error("解析失败：走sql");
        }
        try{
            if(sysTenant == null){
                sysTenant = sysTenantService.getOne(new LambdaQueryWrapper<SysTenant>().eq(SysTenant::getTenantId, one.getTenantId()));
            }
            if(sysTenant != null){
                JSONObject jsonObjectRequest = new JSONObject();
                jsonObjectRequest.put("iccid", one.getIccid());
                jsonObjectRequest.put("telephone", one.getTelephone());
                jsonObjectRequest.put("sendType", 2); // 异常
                jsonObjectRequest.put("agentId", one.getAgentId());
                jsonObjectRequest.put("tenantId", one.getTenantId());
                jsonObjectRequest.put("exceptionMessage", exceptionMessage);
                cn.hutool.http.HttpResponse jsonResponse = HttpRequest.post(sysTenant.getDomain() + "/api/sendMessage")
                // cn.hutool.http.HttpResponse jsonResponse = HttpRequest.post("http://127.0.0.1:8086" + "/api/sendMessage")
                        .body(jsonObjectRequest.toJSONString())
                        .header("Content-Type", "application/json")
                        .execute();
            }
        }catch (Exception e){
            log.error("发送message失败:=======>{}", e.getMessage());
        }
        try{
            // return R.ok();
           return mcSimExceptionService.save(mcSimException) ? R.ok() : R.fail();
        }catch (Exception e){
            log.error("abnormalMonitoring:=======>" + JSONObject.toJSONString(push), e);
            return R.fail("系统错误");
        }
    }
    /**
     * 电信业务报竣-修改卡达量断网功能 推送
     *
     * @param push
     * @return
     */
    @PostMapping(value = "/daLiangPush", consumes = {"application/xml", "text/xml"})
    @ResponseBody
    public HttpResponse daLiangPush(@RequestBody PushDaliang push) {
        if(push == null || StringUtils.isEmpty(push.getIccid())) {
            return R.fail("上送参数有误");
        }
        if(!"竣工".equals(push.getStatusInfo())){
            return R.fail(push.getStatusInfo());
        }
        // 为达量断网操作
        if("100052".equals(push.getAcceptType())){
            McSimDx mcSimDx = new McSimDx();
            mcSimDx.setIccid(push.getIccid());
            mcSimDx.setTelephone(push.getTelephone());
            String isOutThreshold = "";
            log.info("daLiangPush:报竣达量断网=======>" + JSONObject.toJSONString(push));
            if(push.getData() != null && CollUtil.isNotEmpty(push.getData().getAfterAttrs())){
                for(PushDaliang.Attrs attr : push.getData().getAfterAttrs()){
                    if("断网阀值".equals(attr.getChangeattrname())){
                        isOutThreshold = attr.getAfterAttrs();
                        break;
                    }
                }
            }
            if(StringUtils.isEmpty(isOutThreshold)){
                return R.fail("达量断网阀值为空");
            }
            mcSimDx.setIsOutThreshold(isOutThreshold);
            try{
                return mcSimDxService.updateMcSimDx(mcSimDx) > 0 ? R.ok() : R.fail();
            }catch (Exception e){
                log.error("daLiangPush:=======>" + JSONObject.toJSONString(push), e);
                return R.fail("系统错误");
            }
        }
        return R.ok();
    }
    /**
     * 网络会话开始时电信自动化调用
     *
     * @param push
     * @return
     */
    @PostMapping(value = "/sessionStart", consumes = {"application/xml", "text/xml"})
    @ResponseBody
    public HttpResponse sessionStart(@RequestBody PushSession push) {
        return sessionService.handleSessionStart(push);
    }
    /**
     * 网络会话不在线一小时或几小时电信自动化调用
     *
     * @param push
     * @return
     */
    @PostMapping(value = "/sessionEndTime", consumes = {"application/xml", "text/xml"})
    @ResponseBody
    public HttpResponse sessionEndTime (@RequestBody PushSession push) {
        return sessionService.handleSessionEnd(push);
    }
    private HttpResponse activeSim(Push push) {
        if (push == null || StringUtils.isEmpty(push.getIccid())) {
            return null;
        }
        McSimDx sim = simDxMapper.selectOne(new LambdaQueryWrapper<McSimDx>().eq(McSimDx::getIccid, push.getIccid()));
        if (sim == null) {
            log.info("updateArriveTime:查询卡异常=======");
            return R.fail("查询卡异常");
        }
        if (!StringUtils.isEmpty(sim.getActiveTime())) {
            log.info("updateArriveTime:已激活=======");
            return R.fail("已激活");
        }
        Date today = new Date();
        if (push != null && push.getSendTime() != null && push.getSendTime().length() >= 8) {
            today = DateUtils.strToDate(push.getSendTime().substring(0, 8));
        }
        McSimDx mcSimDx = new McSimDx();
        mcSimDx.setIccid(sim.getIccid());
        mcSimDx.setActiveTime(DateUtils.dateToStr(today));
        if(StringUtils.isEmpty(sim.getShouliTime())){
            mcSimDx.setShouliTime(DateUtils.dateToStr(today));
        }
        if (StringUtils.isEmpty(sim.getArriveTime())) {
            log.info("updateArriveTime体验套餐开始操作iccid:"+sim.getIccid());
            SysTenantConfig sysTenantConfig = sysTenantConfigService.queryByTenantId(sim.getTenantId());
            if(sysTenantConfig != null && "0".equals(sysTenantConfig.getIsOpenExp())){
                log.info("打开了体验套餐配置:"+sim.getIccid());
                mcSimDx.setArriveTime(DateUtils.dateToStr(DateUtils.addDay(today, sysTenantConfig.getExpDateCount().intValue())));
                // 如果当前SIM卡设置了套餐 但没设置到期日期 ，则认定为套餐激活后生效
                if(mcSimDx.getPackageId() != null && !StringUtils.isEmpty(mcSimDx.getSku())){
                    List<McProductNorms> mcProductNorms = mcProductNormsMapper.selectPackage(new LambdaQueryWrapper<McProductNorms>().eq(McProductNorms::getId, sim.getPackageId()));
                    if(CollUtil.isNotEmpty(mcProductNorms)){
                        McProductNorms norm = mcProductNorms.get(0);
                        mcSimDx.setArriveTime(DateUtils.dateToStr(DateUtils.addMonth(today, Integer.parseInt(norm.getDeadline()))));
                    }
                }
            }
//            if ("421922".equals(sim.getTenantId())) {
//                sim.setArriveTime(DateUtils.dateToStr(DateUtils.addDay(today, 7)));
//                log.info("updateArriveTime:夜鹰修改到期时间=======");
//            } else if ("760128".equals(sim.getTenantId())) {
//                sim.setArriveTime(DateUtils.dateToStr(DateUtils.addDay(today, 5)));
//                log.info("updateArriveTime:荧飞修改到期时间=======");
//            }
        }
        return mcSimDxService.updateMcSimDx(mcSimDx) > 0 ? R.ok() : R.fail();
    }


    @PostMapping("/statusCallback")
    @ResponseBody
    public HttpResponse statusCallback(@RequestBody SMSStatusCallback statusCallback) {
        log.info("================enter statusCallback");
        log.info(statusCallback.toString());
        McSms sms = smsMapper.selectOne(new LambdaQueryWrapper<McSms>().eq(McSms::getMsgId, statusCallback.getMsgId()));
        if (sms == null) {
            return R.fail("异常");
        }
        sms.setStatus(statusCallback.getMsgStatus());
        sms.setUpdateTime(new Date());
        smsMapper.updateById(sms);

        return R.ok();
    }

    @PostMapping("/returnCallback")
    @ResponseBody
    public HttpResponse returnCallback(@RequestBody SMSReturnCallback returnCallback, HttpServletRequest request) {
        log.info("================enter returnCallback");
        log.info(returnCallback.toString());
        McSimDx sim = simDxMapper.selectOne(new LambdaQueryWrapper<McSimDx>().eq(McSimDx::getTelephone, returnCallback.getPhone()));
        if (sim == null) {
            return R.fail("查询卡异常");
        }
        Date date = new Date();
        McSms sms = new McSms();
        sms.setIccid(sim.getIccid());
        sms.setTelephone(returnCallback.getPhone());
        sms.setContent(returnCallback.getReturnMsgContent());
        sms.setSendtime(date);
        sms.setSendType("设备上行");
        sms.setUrl(request.getRequestURL().toString());
        sms.setMsgId(returnCallback.getMsgId());
        sms.setTenantId(sim.getTenantId());
        sms.setDelFlag("0");
        sms.setCreateTime(date);
        sms.setUpdateTime(date);
        sms.setStatus("1300");
        smsMapper.insert(sms);
        return R.ok();
    }

    /**
     * 翼控推送
     * @param ykResultBean
     * @return
     */
    @PostMapping("/YkCallback")
    @ResponseBody
    public HttpResponse YkCallback(@RequestBody YKResultBean ykResultBean) {
        log.info("================enter YkCallback：{}",JSONObject.toJSONString(ykResultBean));
        // McSimDx sim = simDxMapper.selectOne(new LambdaQueryWrapper<McSimDx>().eq(McSimDx::getIccid, ykResultBean.getIccid()));
        if (StringUtils.isEmpty(ykResultBean.getIccid())) {
            return R.fail("翼控推送参数异常");
        }
        LambdaUpdateWrapper<McSimDx> lambdaUpdateWrapper = new LambdaUpdateWrapper<McSimDx>()
                .eq(McSimDx::getIccid, ykResultBean.getIccid()).eq(McSimDx::getTelephone, ykResultBean.getMsisdn());
        lambdaUpdateWrapper.set(McSimDx::getUpdateTime, LocalDateTime.now());
        // 状态变更状态
        if(ykResultBean.getChangedField().equals("SIM_STATUS")){
            if("去激活".equals(ykResultBean.getNewValue())){
                lambdaUpdateWrapper.set(McSimDx::getNetworkOutage, 1);
            }
            if("已激活".equals(ykResultBean.getNewValue())){
                lambdaUpdateWrapper.set(McSimDx::getNetworkOutage, 0);
            }
            if("停机".equals(ykResultBean.getNewValue()) || "拆机".equals(ykResultBean.getNewValue())){
                lambdaUpdateWrapper.set(McSimDx::getStatus, 5);
                lambdaUpdateWrapper.set(McSimDx::getNetworkOutage, 1);
            }
            simDxMapper.update(lambdaUpdateWrapper);
        }
        // 机卡分离状态
        if(ykResultBean.getChangedField().equals("CARD_IMEI_STATUS")){
            if("1".equals(ykResultBean.getNewValue())){
                lambdaUpdateWrapper.set(McSimDx::getImPayStatus, 1);
            }
            if("0".equals(ykResultBean.getNewValue())){
                lambdaUpdateWrapper.set(McSimDx::getImPayStatus, 0);
            }
            simDxMapper.update(lambdaUpdateWrapper);
        }
        // SIM卡imei变更
        if(ykResultBean.getChangedField().equals("SIM_IMEI")){
            lambdaUpdateWrapper.set(McSimDx::getImei, ykResultBean.getNewValue());
            simDxMapper.update(lambdaUpdateWrapper);
        }
        return R.ok();
    }
    // 发送语音电话
    private void sendPhone(){
        List<McCallPhoneSetting> lists = mcCallPhoneSettingService.list();
        if(CollUtil.isNotEmpty(lists)){
            lists.stream().forEach(item ->{
                if("0".equals(item.getStatus())){
                    try{
                        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                                .accessKeyId(accessKeyId)
                                .accessKeySecret(accessKeySecret)
                                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                                .build());
                        AsyncClient client = AsyncClient.builder()
                                .region("cn-hangzhou") // Region ID
                                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                                .credentialsProvider(provider)
                                .overrideConfiguration(
                                        ClientOverrideConfiguration.create()
                                                // Endpoint 请参考 https://api.aliyun.com/product/Dyvmsapi
                                                .setEndpointOverride("dyvmsapi.aliyuncs.com")
                                        //.setConnectTimeout(Duration.ofSeconds(30))
                                )
                                .build();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("name",item.getName());
                        // Parameter settings for API request
                        SingleCallByTtsRequest singleCallByTtsRequest = SingleCallByTtsRequest.builder()
                                .ttsCode(item.getTtsCode())
                                .calledNumber(item.getPhone())
                                .ttsParam(jsonObject.toJSONString())
                                .build();
                        CompletableFuture<SingleCallByTtsResponse> response = client.singleCallByTts(singleCallByTtsRequest);
                        SingleCallByTtsResponse resp = response.get();
                        client.close();
                        log.error("发送语音电话成功:=====");
                    }catch (Exception e){
                        log.error("发送语音电话失败:=====",e);
                    }
                }
            });
        }
    }
}







